package com.crm.controller.productionController;

import com.crm.exception.ServiceException;
import com.crm.pojo.ProductionDetail;
import com.crm.pojo.Productioncategory;
import com.crm.service.productionService.ProductionCategoryServiceImpl;
import com.crm.service.productionService.ProductionDetilsService;
import com.crm.vo.Result;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class PDetilsController {
    @Autowired
    private ProductionDetilsService productionDetilsService;
    @Autowired
    private ProductionCategoryServiceImpl productionCategoryService;

    //产品页面
    @GetMapping("pDetils")
    public String pDetils() {
        return "product/productionTable";
    }

    //查找所有的产品(未分页)
    @PostMapping("allPro")
    @ResponseBody
    public List<ProductionDetail> allPro() {
        return productionDetilsService.allProductions();
    }

    //分页查找所有的产品
    @PostMapping("allProPaged")
    @ResponseBody
    public Map allProPaged(int page, int rows) {
        Long total = productionDetilsService.queryCount();
        List<ProductionDetail> pro = productionDetilsService.allProductionsPaged(page, rows);
        HashMap map = new HashMap<>();
        map.put("total", total);
        map.put("rows", pro);
        return map;
    }
    //查询最大级数
    @PostMapping("maxdepth")
    @ResponseBody
    public int maxDepth(){
        return productionCategoryService.queryMaxD();
    }

    //新增产品表单
    @GetMapping("to-form-pro-add")
    public String toproForm() {
        return "product/proAddForm";
    }

    //提交新增产品表单
    @PostMapping("newPro-form-sub")
    @ResponseBody
    public Result proFormsub(ProductionDetail productionDetail, @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) {
        try {
            productionDetail.setProductionDetailsIsDel("未删除");
            if (!file.isEmpty()) {
                //获取上下文
                ServletContext servletContext = request.getServletContext();
                //在项目中设置目录存放图片
                String dir = servletContext.getRealPath("\\productionsphotos");
                String dirZoomO = servletContext.getRealPath("\\productionsphotosZoomOut");
                //创建文件夹
                File uploads = new File(dir);
                File uploadsZO = new File(dirZoomO);
                //不存在，则创建目录
                if (!uploads.exists()) {
                    uploads.mkdirs();
                }
                if (!uploadsZO.exists()) {
                    uploadsZO.mkdirs();
                }
                //获取文件的后缀
                String ext = null;
                int pos = file.getOriginalFilename().lastIndexOf(".");
                if (pos == -1) {
                    ext = "";
                } else {
                    ext = file.getOriginalFilename().substring(pos);
                }
                //将文件名改为唯一的UUID
                String newFileName = UUID.randomUUID().toString().toUpperCase() + ext;
                File fullname = new File(uploads, newFileName);
                file.transferTo(fullname);
                Thumbnails.of(dir + "\\" + newFileName).size(60, 60).toFile(dirZoomO + "\\" + newFileName);
                productionDetail.setPimg(newFileName);
            }
            productionDetilsService.addPro(productionDetail);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("添加产品失败！");
        }
    }

    //转发到产品高清图片页
    @GetMapping("to-proImgZoomIn")
    public String toProImgZoomIn() {
        return "product/proImgZoomIn";
    }

    //批量删除产品
    @PostMapping("pros-del")
    @ResponseBody
    public Result prosDelete(String rowsId) {
        try {
            String[] idsS = rowsId.split(",");
            Long[] ids = new Long[idsS.length];
            for (int i = 0; i < idsS.length; i++) {
                ids[i] = Long.parseLong(idsS[i]);
                ProductionDetail productionDetail = productionDetilsService.queryOneById(ids[i]);
                productionDetilsService.deleteproduction(productionDetail);
            }
            return Result.SUCCESS;
        } catch (ServiceException e) {
            e.printStackTrace();
            return new Result("删除失败！");
        }
    }

    //打开产品详情表单
    @GetMapping("to-form-pro-details")
    public String toFormProDetails() {
        return "product/proDetails";
    }

    //打开产品编辑表单
    @GetMapping("to-form-pro-update")
    public String toFormProUpdate() {
        return "product/proEdit";
    }

    //根据pid查看一个产品信息
    @GetMapping("getRowData2")
    @ResponseBody
    public ProductionDetail getRowData2(Long pid) {
        ProductionDetail productionDetail = productionDetilsService.queryOneById(pid);
        if(productionDetail.getPcategory()==null){
            productionDetail.setpCategoryname("暂无分类");
        }else {
            Productioncategory productioncategory = productionCategoryService.queryOneById(productionDetail.getPcategory());
            productionDetail.setpCategoryname(productioncategory.getPcname());
        }
        return productionDetail;
    }

    //修改产品信息
    @PostMapping("editPro-form-sub")
    @ResponseBody
    public Result editProForm(ProductionDetail productionDetail, @RequestParam(value = "file", required = false) CommonsMultipartFile file, HttpServletRequest request) {
        try {
            productionDetail.setProductionDetailsIsDel("未删除");
            if (!file.isEmpty()) {
                //获取上下文
                ServletContext servletContext = request.getServletContext();
                //在项目中设置目录存放图片
                String dir = servletContext.getRealPath("\\productionsphotos");
                String dirZoomO = servletContext.getRealPath("\\productionsphotosZoomOut");
                //创建文件夹
                File uploads = new File(dir);
                File uploadsZO = new File(dirZoomO);
                //不存在，则创建目录
                if (!uploads.exists()) {
                    uploads.mkdirs();
                }
                if (!uploadsZO.exists()) {
                    uploadsZO.mkdirs();
                }
                //获取文件的后缀
                String ext = null;
                int pos = file.getOriginalFilename().lastIndexOf(".");
                if (pos == -1) {
                    ext = "";
                } else {
                    ext = file.getOriginalFilename().substring(pos);
                }
                //将文件名改为唯一的UUID
                String newFileName = UUID.randomUUID().toString().toUpperCase() + ext;
                File fullname = new File(uploads, newFileName);
                file.transferTo(fullname);
                Thumbnails.of(dir + "\\" + newFileName).size(60, 60).toFile(dirZoomO + "\\" + newFileName);
                productionDetail.setPimg(newFileName);
            }else {
                productionDetail.setPimg(productionDetilsService.queryOneById(productionDetail.getPid()).getPimg());
            }
            if(productionDetail.getpCategoryname().equals("暂无分类")){
            }else if(productionDetail.getpCategoryname().equals("")) {
                //分类置空
                productionDetail.setPcategory(null);
            }else {
                if(productionDetail.getpCategoryname().matches(("[0-9]{1,}"))){
                    productionDetail.setPcategory(Long.parseLong(productionDetail.getpCategoryname()));
                }else {
                    productionDetail.setPcategory(productionDetilsService.queryOneById(productionDetail.getPid()).getPcategory());
                }
            }
            productionDetilsService.updateProduction(productionDetail);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("未完成修改，修改失败！");
        }
    }
    //模糊查询id和产品名称
    @PostMapping("/queryBypnameOrpidMh")
    @ResponseBody
    public List<ProductionDetail> querypnameOrpidmh(String q, String b){
        List<ProductionDetail> productionDetails=null;
            if(b.equals("c1")){
                 productionDetails = productionDetilsService.queryBypidOrpnameMh1(q);
            }
            else if(b.equals("c2")){
                productionDetails = productionDetilsService.queryBypidOrpnameMh2(q);
            }
            else{
                String depth = b.substring(1,b.length()-3);
                System.out.println(depth);
                productionDetails = productionDetilsService.queryBypidOrpnameMh3(q, depth);
            }
            for (ProductionDetail p:productionDetails) {
                if(p.getPcategory()!=null) {
                    p.setpCategoryname(productionCategoryService.queryOneById(p.getPcategory()).getPcname());
                }
            }
        return productionDetails;
    }
    //产品高级查询表单提交
    @PostMapping("Pro-form-hlq-sub")
    @ResponseBody
    public Map proFormhlq(ProductionDetail productionDetail, int page, int rows){
        Map map = new HashMap<>();
        Long count = productionDetilsService.proHlqCount(productionDetail);
        List<ProductionDetail> pro = productionDetilsService.proHlq(productionDetail,page,rows);
        for (ProductionDetail p:pro) {
            if(p.getPcategory()!=null) {
                p.setpCategoryname(productionCategoryService.queryOneById(p.getPcategory()).getPcname());
            }
        }
        map.put("total",count);
        map.put("rows",pro);
        return map;
    }
    //打开高级查询表单
    @GetMapping("to-form-pro-highLevel")
    public String toFormProHighLevel(){
        return "product/formProhl";
    }
}
